package com.huak.zookeeper.distributedlock.service.impl;

import com.huak.zookeeper.distributedlock.entity.Product;
import com.huak.zookeeper.distributedlock.repository.ProductRepository;
import com.huak.zookeeper.distributedlock.service.ProductService;
import com.huak.zookeeper.distributedlock.util.DistributedLock;
import com.huak.zookeeper.distributedlock.util.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author liuhuan
 * @date 2018/11/20 09:44
 * @description
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    private static final long EXPIRE_TIME=3000;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private DistributedLock lock;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean updateCountById(Integer id,Integer number) {
        lock.getLock();
        Product p=productRepository.getOne(id);
        Integer count=p.getProductCount();
        int result=0;
        if(p==null){
            log.error("下单失败，要买的商品不存在");
            result=1;
            lock.releaseLock();
            return false;

        }
        if(count<number){
            result=1;
            log.error("下单失败，要买的商品库存不够，当前库存：{},下单数量:{}",count,number);
            lock.releaseLock();
            return false;
        }
        p.setProductCount(count-number);

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//            lock.releaseLock();
//        }

        productRepository.save(p);
        lock.releaseLock();
        return true;


    }

    @Override
    public boolean updateCountById(Integer id) {

        Integer number=1;
        String value=String.valueOf(System.currentTimeMillis()+EXPIRE_TIME);

        try {
            if(redisLock.getLock(String.valueOf(id),value)){
                String countString=stringRedisTemplate.opsForValue()
                        .get("product_"+id);

                if(countString==null){
                    Product p=productRepository.getOne(id);
                    countString=String.valueOf(p.getProductCount());
                    stringRedisTemplate.opsForValue()
                            .set("product_"+id,String.valueOf(p.getProductCount()));
                }
                log.info("获取锁成功");

                if(Integer.parseInt(countString)<number){

                    log.error("下单失败，要买的商品库存不够，当前库存：{},下单数量:{}",countString,number);
                    redisLock.unlock(String.valueOf(id),value);
                    return false;
                }




                //productRepository.save(p);
                decrementCount(id);
                redisLock.unlock(String.valueOf(id),value);
                return true;
            }

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//            redisLock.unlock(String.valueOf(id),value);
//        }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisLock.unlock(String.valueOf(id),value);
        }




        return false;
    }

    private void decrementCount(Integer key){


        stringRedisTemplate.opsForValue().increment("product_"+key,-1);
        String dd=stringRedisTemplate.opsForValue().get("product_"+key);
        if(Integer.valueOf(dd)<=0){
            stringRedisTemplate.opsForValue().getOperations().delete("product_"+key);
        }
    }
}
